/**
 * Created by Weizehua on 2017/2/11.
 */

export function keysCopy(obj: any, type: any): any {
    if (type.constructor === Object) {
        let res = {};
        for (let key of Object.keys(type)) {
            res[key] = keysCopy(obj[key], type[key]);
        }
        return res;
    }
    else if (type.constructor === Array) {
        let res = [];
        let value = obj;
        let typeParam = type[0];
        for (let val of value) {
            res.push(keysCopy(val, typeParam))
        }
        return res;
    }
    else {
        if (obj instanceof Object) {
            let o = {};
            for (let key in obj) {
                o[key] = keysCopy(obj[key], true);
            }
            return o;
        }
        return obj;
    }
}

export function keysExist(obj: any, keys: any) {
    if (keys.constructor === Object) {
        for (let key of Object.keys(keys)) {
            if (!keysExist(obj[key], keys[key]))
                return false;
        }
        return true;
    }
    else if (keys.constructor === Array) {
        if (obj.constructor !== Array)
            return false;
        for (let key of Object.keys(obj)) {
            if (!keysExist(obj[key], keys[0])) {
                return false;
            }
        }
        return true;
    }
    else
        return obj !== undefined;
}

export function access(obj: Object, root: string): any {
    let paths = root;
    if (paths[0] === '.')
        paths = paths.substr(1);
    let objs = paths.split('.');
    while (objs.length) {
        let key = objs.shift();
        if (key)
            obj = obj[key]
    }
    return obj;
}

//noinspection JSUnusedGlobalSymbols
export function install() {
    Object.prototype['access'] = access;
    Object.prototype['keysExist'] = keysExist;
    Object.prototype['keysCopy'] = keysCopy;
}
